#!/usr/bin/python
# -*- coding: utf-8 -*-
# File shell_communication.py

import const
import urllib
from  pipe_communication import PipeCommunication

class ShellCommunication:
    """Provide Shell Intervafe of the Robot use Pipe

    This class pack command from shell to standant
    format; unpack and send message from Robot to shell
    """

    def __init__( self ):
        self.pipe = PipeCommunication( const.PIPE_INPUT, const.PIPE_OUTPUT )
        self.message_buffer = ''
        pass

    def close():
        self.pipe.close()
        pass

    def read( self ):
        message = self.pipe.read()
        
        if not message and not self.message_buffer:
            return None

        self.message_buffer = "".join( ( self.message_buffer, message ) )
        list = self.message_buffer.split( '\n', 1 )

        if len(list) == 2:
            unquote_message = urllib.unquote( list[0] )
            command = { 'type' : const.SHELL_COMMAND,
                        'text' : unquote_message }
            self.message_buffer = list[1]
            return command
        else:
            self.message_buffer = list[0]
            return None

    def write( self, message ):
        if message['type'] == const.SHELL_RESULT:

            quote_message = urllib.quote( message['text'] )
            trail_message = "".join( ( quote_message, '\n' ) )

            return self.pipe.write( trail_message )

        elif message['type'] == const.SHELL_CONTROL:

            trail_message = "".join( ( message['text'].strip(), '\n' ) )

            return self.pipe.write( trail_message )

        return UNKNOW_TYPE

def main():
    shell = ShellCommunication()
    print 'create shell'
    import time
    while True:
        command = shell.read()
        if command:
            print command['text']
            command['type'] = const.SHELL_RESULT
            shell.write( command )
            command['type'] = const.SHELL_CONTROL
            command['text'] = const.SHELL_CONTROL_END
            shell.write( command )

        time.sleep( 1 )

if __name__ == '__main__':
    main()

# End of shell_communication.py
